package com.dhz.common.base;

import java.io.Serializable;

/**
 * <p>服务统一返回数据封装类;</p>
 * <ul>
 *     <li>code -- 业务处理结果代码，0表示成功，其他则有异常，对照返回调用码{@link Code}</li>
 *     <li>msg --  业务提示消息，成功时将不会返回任何内容，异常情况将在该字段返回异常提示</li>
 *     <li>data -- 业务返回数据，任意类型</li>
 * </ul>
 * <pre>
 * exp1:
 *     {
 *         "code":-1,
 *         "msg":"服务器错误"
 *     }
 * exp2:
 *     {
 *         "code":0,
 *         "data":{
 *             "access_token":"ACCESS_TOKEN",
 *             "expires_in":7200
 *         }
 *     }
 * </pre>
 */
public class ServiceResult<T> implements Serializable {

    private int code;
    private String msg;
    private T data;

    private ServiceResult(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public ServiceResult(Code code, String msg, T data) {
        this(code.getValue(), msg, data);
    }

    public ServiceResult(Code code, String msg) {
        this(code.getValue(), msg, null);
    }

    public ServiceResult(Code code, T data) {
        this(code.getValue(), null, data);
    }

    public ServiceResult(Code code) {
        this.code = code.getValue();
    }

    public ServiceResult setUp(Code code, String msg, T data) {
        this.code = code.getValue();
        this.msg = msg;
        this.data = data;
        return this;
    }

    public ServiceResult setUp(Code code, String msg) {
        return setUp(code, msg, null);
    }

    public ServiceResult setUp(Code code, T data) {
        return setUp(code, null, data);
    }

    public ServiceResult setUp(Code code) {
        return setUp(code, null, null);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
